package com.i360day.invoker.loadbalancer;

import com.i360day.invoker.RequestTemplate;
import com.i360day.invoker.http.InvokerClient;
import com.i360day.invoker.http.Request;
import com.i360day.invoker.http.Response;
import com.i360day.invoker.request.HttpInvokerRequest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;

import java.io.IOException;
import java.net.URI;

public class HttpInvokerCloudLoadBalancerClient implements HttpInvokerRequest {

    private final InvokerClient delegate;
    private final LoadBalancerClient loadBalancerClient;

    public HttpInvokerCloudLoadBalancerClient(InvokerClient delegate, LoadBalancerClient loadBalancerClient) {
        this.delegate = delegate;
        this.loadBalancerClient = loadBalancerClient;
    }

    @Override
    public Response executor(RequestTemplate requestTemplate) throws IOException {
        Request request = Request.of(URI.create(requestTemplate.getUri()), requestTemplate);
        final URI originalUri = request.getUri();
        String serviceId = originalUri.getHost();
        ServiceInstance instance = loadBalancerClient.choose(serviceId);
        //优先执行IP直连方式
        if (instance == null) {
            return delegate.execute(request);
        }
        //使用注册中心获取方式
        Request of = Request.of(loadBalancerClient.reconstructURI(instance, originalUri), request.requestTemplate());
        return delegate.execute(of);
    }
}
